package com.fingard.dsp.bank.directbank.fngrd01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IQRPay;
import com.fingard.dsp.bank.reqrespobj.qrpay.ReqGenQRInfo;
import com.fingard.dsp.bank.reqrespobj.qrpay.RetAtsGenQRInfo;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqUnifiedOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsUnifiedOrder;
import com.fingard.text.StringHelper;

import java.util.HashMap;

/**
 * 融汇通扫码付
 * 
 * @author Cruise
 * @date 2018/11/14
 */
public class FnGrd01QRPay extends FnGrd01Base implements IQRPay {
	@Override
	public RetAtsGenQRInfo genQRInfo(ReqGenQRInfo p_req) {
		RetAtsGenQRInfo retAts = new RetAtsGenQRInfo();

		try {
			retAts.rdSeq = p_req.rdSeq;

			ActSetItem actItem = getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId, p_req.appId, "unifiedorder");
			if (actItem != null) {
				retAts.respCode = "-1";
				retAts.respInfo = reqHeader.bankCode + "无此接口";
				retAts.qrInfo = "";
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账户、商户或公众号对应的配置";
			}
		} catch (Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.getMessage();

			WriteBankLogLn(LogHelper.getStackTrace(e));
		}

		return retAts;
	}

	/**
	 * 融汇通扫码付获取二维码
	 */
	@Override
	public RetAtsUnifiedOrder submitQROrder(ReqUnifiedOrder p_req) {
		RetAtsUnifiedOrder retAts = new RetAtsUnifiedOrder();
		retAts.rdSeq = p_req.rdSeq;

		try {
			ActSetItem actItem = getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId, p_req.appId, "unifiedorder");
			if (actItem != null) {
				// 下单业务参数

				/** 保融分配的代表某个企业的编号 */
				String enterpriseNum = actItem.inMerchantId;

				/** 商户号 */
				String mchId = actItem.merchantId;

				/** 商户订单号 */
				String outTradeNo = p_req.rdSeq;

				/** 商品描述 */
				String body = p_req.description;

				/** 总金额，单位分 */
				String totalFee = StringHelper.amountMultiply100(p_req.amount);

				/** 订单生成的机器ip */
				String mchCreateIP = actItem.createIP;

				/** 支付结果通知地址 */
				String notifyURL = actItem.notifyURL;

				/** 附加信息，作为扩展，在回调通知中会原样返回 */
				String attach = p_req.attach;

				/** 是否校验支付身份信息，会结合证件类型、证件号、姓名去做身份校验，1：校验，0：不校验，默认0 */
				String isCheckIdentity = "0";
                if ("1".equals(p_req.realNameFlag)) {
                    if ("0".equals(p_req.realNameType)) {
                        isCheckIdentity = "3";
                    } else if ("2".equals(p_req.realNameType)) {
                        isCheckIdentity = "4";
                    } else {
                        isCheckIdentity = "1";
                    }
                } else if ("0".equals(p_req.realNameFlag)) {
                	isCheckIdentity = "0";
                } else {
                    if (StringHelper.hasAnyChar(p_req.oppActName) && StringHelper.hasAnyChar(p_req.certNumber)) {
                    	isCheckIdentity = "1";
                    }
                }

                String organizationId = p_req.orgId;

				/** 是否支持信用卡 */
				//String limitCreditPay = getBankConfig().getValueAsString("limitCreditPay");
				String limitPay = getBankConfig().getValueAsString("limitPay");
				if ("no_credit".equals(limitPay)) {
					limitPay = "1";
				}else{
					limitPay = "0";
				}

				/** 证件类型枚举，默认身份证 */
				String certType = "0";

				/** 证件号 */
				String certNum = p_req.certNumber;

				/** 真实姓名 */
				String custName = p_req.oppActName;

				/** 手机号 */
				String phoneNum = p_req.cellPhone;

				/** 订单生成时间，格式为yyyyMMddHHmmss */
				String timeStart = Format.DateTime14Format.format(p_req.getTimeStart());

				/** 订单失效时间，格式为yyyyMMddHHmmss */
				String timeExpire = Format.DateTime14Format.format(p_req.getTimeExpire());

				/** 缴费成功后是否回调外部系统，00：不回调，01：调用见费，默认为00 */
				String callFlag = "00";

				/** 随机字符串 */
				String nonceStr = get_nonce_str();

				/** 签名 */
				String signature = "";

				HashMap<String, String> mapParams = new HashMap<String, String>();

				mapParams.put("EnterpriseNum", enterpriseNum);
				mapParams.put("MchId", mchId);
				mapParams.put("OutTradeNo", outTradeNo);
				mapParams.put("Body", body);
				mapParams.put("TotalFee", totalFee);
				mapParams.put("MchCreateIp", mchCreateIP);
				mapParams.put("NotifyUrl", notifyURL);
				mapParams.put("Attach", attach);
				mapParams.put("IsCheckIdentity", isCheckIdentity);
                mapParams.put("OrganizationId", organizationId);
				mapParams.put("LimitCreditPay", limitPay);
				mapParams.put("CertType", certType);
				mapParams.put("CertNum", certNum);
				mapParams.put("CustName", custName);
				mapParams.put("PhoneNum", phoneNum);
				mapParams.put("TimeStart", timeStart);
				mapParams.put("TimeExpire", timeExpire);
				mapParams.put("CallFlag", callFlag);
				mapParams.put("NonceStr", nonceStr);
				mapParams.put("timeout_express", getValidTime(p_req.getValidTime()));

				// 签名
				String signStr = getSignStr(mapParams, actItem.saltKey);
				signature = signFnGrd(actItem, signStr);

				mapParams.put("Signature", signature);

				// post请求数据
				String reqPostJson = getReqPostJson(mapParams);
				String reqSendData = getReqSendData(enterpriseNum, reqPostJson);

				// 服务地址
				String url = "";

				/**
				 * 支付宝及微信扫码以commandCode区分
				 *
				 * FGNATIVE01 融汇通扫码支付（微信） 
				 * FGNATIVE02 融汇通扫码支付（支付宝）
				 */
				if ("FGNATIVE01".equals(p_req.reqHeader.commandCode)) {
					url = bankFront.getUrl("submitWXQROrder");
				} else if ("FGNATIVE02".equals(p_req.reqHeader.commandCode)) {
					url = bankFront.getUrl("submitAliQROrder");
				} else if ("UNQRPAY01".equals(p_req.reqHeader.commandCode)) {
					url = bankFront.getUrl("oneCodePaySubmit");
				}

				// 发融汇
				String[] tmpStrRet = sendToFnGrd(reqSendData, url);

				// 解析融汇返回
				if (tmpStrRet[0].length() == 0) {
					if (tmpStrRet[1].indexOf("Status") > 0) {
						JSONObject respJSON = JSON.parseObject(tmpStrRet[1]);

						String status = respJSON.getString("Status");
						if ("-1".equals(status)) {
							retAts.respCode = "-1";
							retAts.respInfo = respJSON.getString("ReturnMsg");

							return retAts;
						}
					} else {
						String respStr = getRespPostData(tmpStrRet[1]);

						JSONObject respJSONObj = JSON.parseObject(respStr);

						String status = respJSONObj.getString("Status");
						if ("0".equals(status)) {
							retAts.respCode = "0";
							retAts.respInfo = respJSONObj.getString("ReturnMsg");

							retAts.qrInfo = respJSONObj.getString("CodeUrl");
							retAts.qrImgUrl = respJSONObj.getString("CodeImgUrl");

							retAts.transState = "SUCCESS";
							retAts.payInfoCode = status;
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = respJSONObj.getString("ReturnMsg");

							return retAts;
						}
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tmpStrRet[1];
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到相应账户、商户或公众号的配置信息";

				return retAts;
			}
		} catch (Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.getMessage();

			WriteBankLogLn(LogHelper.getStackTrace(e));
		}

		return retAts;
	}

	/**
	 * 融汇通扫码付交易状态查询
	 */
	@Override
	public RetAtsQueryOrder queryQRPay(ReqQueryOrder p_req) {
		RetAtsQueryOrder retAts = new RetAtsQueryOrder();
		retAts.rdSeq = p_req.rdSeq;

		try {
			ActSetItem actItem = this.getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId, p_req.appId, "unifiedorder");
			if (actItem != null) {
				// 查询业务参数

				/** 保融分配的代表某个企业的编号 */
				String enterpriseNum = actItem.inMerchantId;

				/** 商户号 */
				String mchId = actItem.merchantId;

				/** 商户订单号 */
				String outTradeNo = p_req.rdSeq;

				/** 随机字符串 */
				String nonceStr = get_nonce_str();

				/** 签名 */
				String signature = "";

				HashMap<String, String> mapParams = new HashMap<String, String>();

				mapParams.put("EnterpriseNum", enterpriseNum);
				mapParams.put("MchId", mchId);
				mapParams.put("OutTradeNo", outTradeNo);
				mapParams.put("NonceStr", nonceStr);

				// 签名
				String signStr = getSignStr(mapParams, actItem.saltKey);
				signature = signFnGrd(actItem, signStr);

				mapParams.put("Signature", signature);

				// post请求数据
				String reqPostJson = getReqPostJson(mapParams);
				String reqSendData = getReqSendData(enterpriseNum, reqPostJson);

				String url = "";

				/**
				 * 支付宝及微信扫码以commandCode区分
				 *
				 * FGNATIVE01 融汇通扫码支付（微信） 
				 * FGNATIVE02 融汇通扫码支付（支付宝）
				 */
				if ("FGNATIVE01".equals(p_req.reqHeader.commandCode)) {
					url = bankFront.getUrl("QueryWXQRPay");
				} else if ("FGNATIVE02".equals(p_req.reqHeader.commandCode)) {
					url = bankFront.getUrl("QueryALiQRPay");
				} else if ("UNQRPAY01".equals(p_req.reqHeader.commandCode)) {
					url = bankFront.getUrl("oneCodePayQuery");
				}

				// 发融汇
				String[] tmpStrRet = sendToFnGrd(reqSendData, url);

				// 解析融汇返回
				if (tmpStrRet[0].length() == 0) {
					if (tmpStrRet[1].indexOf("Status") > 0) {
						JSONObject respJSON = JSON.parseObject(tmpStrRet[1]);

						String status = respJSON.getString("Status");
						if ("-1".equals(status)) {
							retAts.respCode = "-1";
							retAts.respInfo = respJSON.getString("ReturnMsg");

							return retAts;
						}
					} else {
						String respStr = getRespPostData(tmpStrRet[1]);

						JSONObject respJSONObj = JSON.parseObject(respStr);

						String status = respJSONObj.getString("Status");

						retAts.respCode = "0";
						retAts.respInfo = respJSONObj.getString("ReturnMsg");

						if ("0".equals(status)) {
							retAts.transState = StringHelper.joinNotEmpty("+", status, respJSONObj.getString("TradeState"));
							retAts.payInfoCode = respJSONObj.getString("TradeState");

							String outTransID = respJSONObj.getString("Transaction_id");
							if (StringHelper.isNullOrEmpty(outTransID)) {
								outTransID = respJSONObj.getString("BankBillNo");
							}
							retAts.outTransID = outTransID;
							retAts.oppBank = respJSONObj.getString("BankType");
							retAts.openId = respJSONObj.getString("OpenId");
							retAts.payType = "W210".equals(respJSONObj.getString("PayType")) ? "02" : "03";
						} else {
							retAts.transState = StringHelper.joinNotEmpty("+", status, respJSONObj.getString("ReturnMsg"));
							retAts.payInfoCode = respJSONObj.getString("ReturnMsg");
						}
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tmpStrRet[1];
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号"+ p_req.ownAct + "商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		return retAts;
	}
}
